//
//  BIDPublishStoreGoodsViewController.m
//  HJGJCommunity
//
//  Created by mal on 2017/6/17.
//  Copyright © 2017年 mal. All rights reserved.
//

#import "BIDPublishStoreGoodsViewController.h"
#import "BIDPublishStoreGoodsHeaderView.h"
#import "BIDBrowserImageViewController.h"
#import "BIDPublishStoreGoodsCell.h"
#import "BIDAddPhotoView.h"
#import "BIDCustomTextView.h"
#import "ELCImagePickerHeader.h"
#import "BIDUploadFile.h"
#import "UIView+FindFirstResponder.h"

#import <MobileCoreServices/UTCoreTypes.h>

//发布新商品
static NSString *publishURL = @"commodityAndroid/add.action";

//修改
static NSString *editURL = @"commodityAndroid/modify.action";

//下架
static NSString *removeURL = @"commodityAndroid/down.action";

@interface BIDPublishStoreGoodsViewController ()<UITableViewDelegate, UITableViewDataSource, BIDPublishStoreGoodsHeaderViewDelegate, UITextFieldDelegate, ELCImagePickerControllerDelegate, UINavigationControllerDelegate, BIDUploadFileDelegate>
{
    BIDPublishStoreGoodsHeaderView *_headerView;
    NSMutableArray *_dataSourceArr;
    BOOL _isRegister;
    CGRect _desRect;
    BIDUploadFile *_uploadFile;
    //是修改还是新增
    BOOL _isEdit;
}
@end

@implementation BIDPublishStoreGoodsViewController
@synthesize goodsDic;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"发布";
    _dataSourceArr = [NSMutableArray array];
    if(goodsDic)
    {
        _isEdit = YES;
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"下架" style:UIBarButtonItemStylePlain target:self action:@selector(removeHandler)];
    }
    else
    {
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(closeHandelr)];
    }
    //
    _headerView = [[[NSBundle mainBundle] loadNibNamed:@"BIDPublishStoreGoodsHeaderView" owner:self options:nil] lastObject];
    _headerView.delegate = self;
    _headerView.titleTF.inputAccessoryView = self.toolBar;
    _headerView.contentTextView.inputAccessoryView = self.toolBar;
    _headerView.contentTextView.placeholder = @"描述下您的商品";
    _headerView.contentTextView.placeholderColor = RGBACOLOR(190, 190, 196, 1.f);
    _tableView.tableHeaderView = _headerView;
    _tableView.allowsSelection = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    UIButton *footerBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [footerBtn setTitle:@"+添加商品规格" forState:UIControlStateNormal];
    [footerBtn setTitleColor:RGBACOLOR(27, 211, 205, 1.f) forState:UIControlStateNormal];
    [footerBtn.titleLabel setFont:[UIFont systemFontOfSize:15.f]];
    [footerBtn addTarget:self action:@selector(addSectionHandler) forControlEvents:UIControlEventTouchUpInside];
    footerBtn.frame = CGRectMake(0, 0, screenSize.width, 45.f);
    _tableView.tableFooterView = footerBtn;
    //
    NSString *strRequestURL = @"";
    if(_isEdit)
    {
        strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], editURL];
    }
    else
    {
        strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], publishURL];
    }
    _uploadFile = [[BIDUploadFile alloc] initWithURL:strRequestURL];
    _uploadFile.delegate = self;
    //
    [self prepareData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)prepareData
{
    if(goodsDic)
    {
        //修改已发布的商品信息
        NSArray *fileListArr = goodsDic[@"fileList"];
        NSArray *goodsStandardArr = goodsDic[@"specList"];
        _headerView.titleTF.text = goodsDic[@"name"];
        _headerView.contentTextView.text = goodsDic[@"content"];
        if(fileListArr && fileListArr.count>0)
        {
            for(NSDictionary *dic in fileListArr)
            {
                NSString *strFilePath = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], dic[@"path"]];
                [_headerView.addPhotoView addPhotoWithImgURL:[NSURL URLWithString:strFilePath]];
            }
        }
        if(goodsStandardArr && goodsStandardArr.count>0)
        {
            for(NSDictionary *dic in goodsStandardArr)
            {
                NSMutableArray *tempArr = [NSMutableArray array];
                NSDictionary *subDic1 = @{@"title":@"规格说明", @"content":dic[@"spec"], @"placeholder":@"请填写规格说明", @"keyboardType":@"normal"};
                NSDictionary *subDic2 = @{@"title":@"金额(元)", @"content":dic[@"price"], @"placeholder":@"请填写金额", @"keyboardType":@"decimal"};
                [tempArr addObject:subDic1];
                [tempArr addObject:subDic2];
                [_dataSourceArr addObject:tempArr];
            }
        }
        else
        {
            NSArray *arr = @[@[@{@"title":@"规格说明", @"content":@"", @"placeholder":@"请填写规格说明", @"keyboardType":@"normal"}, @{@"title":@"金额(元)", @"content":@"", @"placeholder":@"请填写金额", @"keyboardType":@"decimal"}]];
            _dataSourceArr = [[NSMutableArray alloc] initWithArray:arr];

        }
    }
    else
    {
        NSArray *arr = @[@[@{@"title":@"规格说明", @"content":@"", @"placeholder":@"请填写规格说明", @"keyboardType":@"normal"}, @{@"title":@"金额(元)", @"content":@"", @"placeholder":@"请填写金额", @"keyboardType":@"decimal"}]];
        _dataSourceArr = [[NSMutableArray alloc] initWithArray:arr];
    }
    _tableView.tableHeaderView = _headerView;
     [_tableView reloadData];
}

- (void)closeHandelr
{
    [self dismissViewControllerAnimated:YES completion:^{}];
}

- (void)alertViewHandler:(id)obj
{
    NSNumber *value = (NSNumber *)obj;
    if([value intValue]==101)
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
    else
    {
        [self dismissViewControllerAnimated:YES completion:^{}];
    }
}

/**
 下架
 */
- (void)removeHandler
{
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], removeURL];
    NSString *strPost = [[NSString alloc] initWithFormat:@"commodity.id=%@&commodity.isUp=0", goodsDic[@"id"]];
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
        if(errMsg)
        {
            [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
        else
        {
            [self showAlertView:@"商品下架成功" buttonTitle:ALERT_BTN_TITLE tag:@101 functionName:@"alertViewHandler:"];
        }
    }];
}

/**
 添加规格
 */
- (void)addSectionHandler
{
    NSArray *arr = @[@[@{@"title":@"规格说明", @"content":@"", @"placeholder":@"请填写规格说明", @"keyboardType":@"normal"}, @{@"title":@"金额(元)", @"content":@"", @"placeholder":@"请填写金额", @"keyboardType":@"number"}]];
    [_dataSourceArr addObjectsFromArray:arr];
    [_tableView insertSections:[NSIndexSet indexSetWithIndex:_dataSourceArr.count-1] withRowAnimation:UITableViewRowAnimationAutomatic];
}

/**
 发布

 @param sender <#sender description#>
 */
- (IBAction)publishBtnHandler:(id)sender
{
    if(_headerView.titleTF.text.length == 0)
    {
        [self showAlertView:@"请填写商品名称" buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        return ;
    }
    if(_headerView.contentTextView.text.length == 0)
    {
        [self showAlertView:@"请填写商品描述" buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        return;
    }
    for(NSArray *arr in _dataSourceArr)
    {
        for(NSDictionary *dic in arr)
        {
            NSString *strText = ANY2NSSTRING(dic[@"content"]);
            if(strText.length == 0)
            {
                NSString *strMsg = [[NSString alloc] initWithFormat:@"请填写%@", dic[@"title"]];
                [self showAlertView:strMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
                return;
            }
        }
    }
    NSString *strGoodsTitle = _headerView.titleTF.text;
    NSString *strGoodsDescription = _headerView.contentTextView.text;
    if(_headerView.addPhotoView.imgArr.count > 0)
    {
        if(_isEdit)
        {
            [_uploadFile addData:@"commodity.id" value:goodsDic[@"id"]];
        }
        [_uploadFile addData:@"memberId" value:[AppDelegate getUserId]];
        [_uploadFile addData:@"commodity.name" value:strGoodsTitle];
        [_uploadFile addData:@"commodity.content" value:strGoodsDescription];
        NSString *strGoodsStandard = [self transformGoodsStandardDescription];
        [_uploadFile addData:@"specList" value:strGoodsStandard];
        int count = 0;
        for(UIImage *img in _headerView.addPhotoView.imgArr)
        {
            count++;
            NSString *strFileName = [[NSString alloc] initWithFormat:@"fileName%d.jpg", count];
            NSData *imgData = UIImageJPEGRepresentation(img, 0.5f);
            [_uploadFile addFileFromMemory:strFileName fieldName:@"fileUploads" data:imgData];
            [_uploadFile addData:@"fileUploadsFileName" value:strFileName];
        }
        [_uploadFile finishAddFile];
        [_uploadFile startUpload];
    }
    else
    {
        NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], publishURL];
        NSMutableString *strPost = [NSMutableString string];
        [strPost appendFormat:@"memberId=%@", [AppDelegate getUserId]];
        if(_isEdit)
        {
            [strPost appendFormat:@"&commodity.id=%@", goodsDic[@"id"]];
        }
        [strPost appendFormat:@"&commodity.name=%@", strGoodsTitle];
        [strPost appendFormat:@"&commodity.content=%@", strGoodsDescription];
        NSString *strGoodsStandard = [self transformGoodsStandardDescription];
        [strPost appendFormat:@"&specList=%@", strGoodsStandard];
        [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
            if(errMsg)
            {
                [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
            }
            else
            {
                if(_isEdit)
                {
                    [self showAlertView:@"发布成功" buttonTitle:ALERT_BTN_TITLE tag:@101 functionName:@"alertViewHandler:"];
                }
                else
                {
                    [self showAlertView:@"发布成功" buttonTitle:ALERT_BTN_TITLE tag:@100 functionName:@"alertViewHandler:"];
                }
            }
        }];
    }
}

/**
 把商品规格数组转换成后台需要的格式

 @return <#return value description#>
 */
- (NSString *)transformGoodsStandardDescription
{
    NSMutableArray *desArr = [NSMutableArray array];
    for(NSArray *arr in _dataSourceArr)
    {
        NSDictionary *dic1 = arr[0];
        NSDictionary *dic2 = arr[1];
        NSDictionary *desDic = @{@"spec":dic1[@"content"], @"price":dic2[@"content"]};
        [desArr addObject:desDic];
    }
    NSError *err;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:desArr options:NSJSONWritingPrettyPrinted error:&err];
    NSString *strDes = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return strDes;
}

/**
 键盘显示与隐藏
 
 @param notification <#notification description#>
 */
- (void)keyboardWillShow:(NSNotification *)notification
{
    NSDictionary *info = [notification userInfo];
    CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    self.keyboardHeight = keyboardSize.height;
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:0.25f];
    UIView *tempView = [self.view findFirstResponder];
    if([tempView isKindOfClass:[UITextField class]])
    {
        if(_desRect.origin.y+_desRect.size.height > CGRectGetHeight(self.view.frame)-self.keyboardHeight)
        {
            self.distanceToMove = _desRect.origin.y+_desRect.size.height-(CGRectGetHeight(self.view.frame)-self.keyboardHeight);
            CGPoint pt = _tableView.contentOffset;
            pt.y += self.distanceToMove;
            [_tableView setContentOffset:pt animated:YES];
        }
    }
    
    [UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:0.30f];
    CGPoint pt = _tableView.contentOffset;
    if(pt.y-self.distanceToMove < 0)
    {
        pt.y = 0;
    }
    else
    {
        pt.y -= self.distanceToMove;
    }
    [_tableView setContentOffset:pt animated:YES];
    [UIView commitAnimations];
}

/**
 删除

 @param btn <#btn description#>
 */
- (void)deleteSectionHandler:(UIButton*)btn
{
    NSInteger index = btn.tag;
    [_tableView beginUpdates];
    [_dataSourceArr removeObjectAtIndex:index];
    [_tableView deleteSections:[NSIndexSet indexSetWithIndex:index] withRowAnimation:UITableViewRowAnimationAutomatic];
    [_tableView endUpdates];
    NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, _dataSourceArr.count)];
    [_tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
}

#pragma mark - UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    NSUInteger section = textField.tag / (_dataSourceArr.count+1);
    NSUInteger row = textField.tag % (_dataSourceArr.count+1);
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
    CGRect rectInTableView = [_tableView rectForRowAtIndexPath:indexPath];
    CGRect rect = [_tableView convertRect:rectInTableView toView:[_tableView superview]];
    _desRect = rect;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    NSUInteger section = textField.tag / (_dataSourceArr.count+1);
    NSUInteger row = textField.tag % (_dataSourceArr.count+1);
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:_dataSourceArr[section][row]];
    [dic setObject:textField.text forKey:@"value"];
    [dic setObject:textField.text forKey:@"content"];
    NSMutableArray *tempArr = [[NSMutableArray alloc] initWithArray:_dataSourceArr[section]];
    [tempArr replaceObjectAtIndex:row withObject:dic];
    [_dataSourceArr replaceObjectAtIndex:section withObject:tempArr];
}

#pragma mark - BIDPublishStoreGoodsHeaderViewDelegate

- (void)choosePhoto
{
    if(_headerView.addPhotoView.imgArr.count == 9)
    {
        NSString *strHint = [[NSString alloc] initWithFormat:@"最多选择%d张图片", 9];
        [self showAlertView:strHint buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        return;
    }
    //
    ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc] initImagePicker];
    
    //3-_addPhotoView.imgArr.count
    elcPicker.maximumImagesCount = 9-_headerView.addPhotoView.imgArr.count; //Set the maximum number of images to select to 100
    elcPicker.returnsOriginalImage = YES; //Only return the fullScreenImage, not the fullResolutionImage
    elcPicker.returnsImage = YES; //Return UIimage if YES. If NO, only return asset location information
    elcPicker.onOrder = YES; //For multiple image selection, display and return order of selected images
    elcPicker.mediaTypes = @[(NSString *)kUTTypeImage]; //Supports image and movie types((NSString *)kUTTypeMovie)
    
    elcPicker.imagePickerDelegate = self;
    
    [self presentViewController:elcPicker animated:YES completion:nil];
}

- (void)resizeViewWithFrame:(CGRect)frame
{
    _tableView.tableHeaderView = _headerView;
}

- (void)showPhotoAtIndex:(NSInteger)index withImgArr:(NSArray *)arr
{
    BIDBrowserImageViewController *vc = [[BIDBrowserImageViewController alloc] initWithNibName:@"BIDBrowserImageViewController" bundle:nil];
    vc.index = index;
    vc.imgArr = [[NSArray alloc] initWithArray:arr];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - BIDUpladFileDelegate
- (void)finishUploadWithResult:(id)obj
{
    if([obj isKindOfClass:[NSDictionary class]])
    {
        NSDictionary *dic = (NSDictionary *)obj;
        NSNumber *value = dic[@"head"][@"success"];
        if([value intValue] == 1)
        {
            if(_isEdit)
            {
                [self showAlertView:@"发布成功" buttonTitle:ALERT_BTN_TITLE tag:@101 functionName:@"alertViewHandler:"];
            }
            else
            {
                [self showAlertView:@"发布成功" buttonTitle:ALERT_BTN_TITLE tag:@100 functionName:@"alertViewHandler:"];
            }
        }
        else
        {
            NSString *strErrMsg = @"";
            if(dic[@"head"][@"msg"])
            {
                strErrMsg = dic[@"head"][@"msg"];
            }
            else
            {
                strErrMsg = @"发布失败";
            }
            [self showAlertView:strErrMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
    }
}

- (void)uploadFailedWithError:(NSError *)err
{
    [self showAlertView:[err localizedDescription] buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
}

#pragma mark - ELCImagePickerControllerDelegate Methods

- (void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info
{
    [self dismissViewControllerAnimated:YES completion:nil];
    
    NSMutableArray *images = [NSMutableArray arrayWithCapacity:[info count]];
    for (NSDictionary *dict in info)
    {
        if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypePhoto)
        {
            if ([dict objectForKey:UIImagePickerControllerOriginalImage])
            {
                UIImage* image=[dict objectForKey:UIImagePickerControllerOriginalImage];
                [images addObject:image];
                [_headerView.addPhotoView addPhoto:image];
            }
            else
            {
                NSLog(@"UIImagePickerControllerReferenceURL = %@", dict);
            }
        }
        else if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypeVideo)
        {
            if ([dict objectForKey:UIImagePickerControllerOriginalImage])
            {
                UIImage* image=[dict objectForKey:UIImagePickerControllerOriginalImage];
                [images addObject:image];
            }
            else
            {
                NSLog(@"UIImagePickerControllerReferenceURL = %@", dict);
            }
        }
        else
        {
            NSLog(@"Uknown asset type");
        }
    }
}

- (void)elcImagePickerControllerDidCancel:(ELCImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _dataSourceArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *arr = _dataSourceArr[section];
    return arr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    static NSString *identifier = @"identifier";
    NSUInteger section = indexPath.section;
    NSUInteger row = indexPath.row;
    if(!_isRegister)
    {
        _isRegister = YES;
        UINib *nib = [UINib nibWithNibName:@"BIDPublishStoreGoodsCell" bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:identifier];
    }
    BIDPublishStoreGoodsCell *standardCell = [tableView dequeueReusableCellWithIdentifier:identifier];
    NSDictionary *dic = _dataSourceArr[section][row];
    standardCell.titleLabel.text = dic[@"title"];
    standardCell.contentTF.text = ANY2NSSTRING(dic[@"content"]);
    standardCell.contentTF.placeholder = dic[@"placeholder"];
    standardCell.contentTF.inputAccessoryView = self.toolBar;
    standardCell.contentTF.tag = section*(_dataSourceArr.count+1)+row;
    standardCell.contentTF.delegate = self;
    if([dic[@"keyboardType"] isEqualToString:@"normal"])
    {
        standardCell.contentTF.keyboardType = UIKeyboardTypeDefault;
    }
    else if([dic[@"keyboardType"] isEqualToString:@"decimal"])
    {
        standardCell.contentTF.keyboardType = UIKeyboardTypeDecimalPad;
    }
    cell = standardCell;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = nil;
    headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(tableView.frame), 20.f)];
    [headerView setBackgroundColor:RGBACOLOR(239, 239, 239, 1.f)];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(14, 0, CGRectGetWidth(headerView.frame)-14*2, CGRectGetHeight(headerView.frame))];
    [label setFont:[UIFont systemFontOfSize:13.f]];
    NSString *strCount = [[NSString alloc] initWithFormat:@"%ld", section+1];
    strCount = [BIDGlobalMethods digit2Capital:strCount];
    NSString *strTitle = [[NSString alloc] initWithFormat:@"商品规格%@", strCount];
    [label setText:strTitle];
    [label setTextColor:RGBACOLOR(130, 130, 130, 1.f)];
    label.textAlignment = NSTextAlignmentLeft;
    [headerView addSubview:label];
    //
    CGFloat btnWidth = 60.f;
    CGFloat btnHeight = CGRectGetHeight(headerView.frame);
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    btn.frame = CGRectMake(CGRectGetWidth(headerView.frame)-btnWidth, 0, btnWidth, btnHeight);
    btn.tintColor = RGBACOLOR(130, 130, 130, 1.f);
    [btn setTitle:@"删除" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(deleteSectionHandler:) forControlEvents:UIControlEventTouchUpInside];
    btn.tag = section;
    [headerView addSubview:btn];
    btn.hidden = section==0?YES:NO;
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20.f;
}

@end
